#!/usr/bin/env python 
# -*- coding:utf-8 -*-
'''
@File    :   handan_tuils.py    
@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2022/4/22 0022 16:10   st      1.0         None
'''
import json
import time

import numpy as np
from pypinyin import Style, lazy_pinyin
from collections import Counter
from similar.sim_cos_utils import similarity_cosine
from utils.constent import *


class BiHua:
    def __init__(self):
        self.load_everything()

    def load_everything(self):
        with open(os.path.join(stroke2vec_dir, 'char_with_num_and_stroke.json'), 'r', encoding='utf-8') as fp:
            self.char_with_num_and_stroke = json.loads(fp.read())
        with open(os.path.join(stroke2vec_dir, 'char_with_num_and_strokeid.json'), 'r', encoding='utf-8') as fp:
            self.char_with_num_and_strokeid = json.loads(fp.read())

    def get_char_with_radical_and_num_and_stroke(self, char):
        return self.char_with_num_and_stroke.get(char)

    # def get_char_with_radical_and_num_and_strokeid(self, char):
    #     return self.char_with_num_and_strokeid[char]

bihua = BiHua()
stroke_index = ['横', '竖', '撇', '捺', '折']

def load_bihua_voc(char):
    vec = np.zeros((5,))
    res = bihua.get_char_with_radical_and_num_and_stroke(char)
    if not res:
        return vec
    stroke_dict = {'横': 0, '竖': 0, '撇': 0, '捺': 0, '折': 0}
    for k in res['stroke_list']:
        if stroke_dict.__contains__(k):
            stroke_dict[k] += 1
    stroke_voc = [stroke_dict[x] for x in stroke_index]
    # for c in ranlen(stroke_voc):
    #     i = int(c)
    #     vec[i - 1] = cnts[c]
    vec += stroke_voc
    return vec


alps = 'abcdefghijklmnopqrstuvwxyz'


def zimu_vec(zi):
    '''
    把字转换成字母向量
    :param zi:
    :return:
    '''
    pinyin: str
    pinyin = lazy_pinyin(zi, style=Style.TONE3)[0]
    if pinyin[-1] in '1234':
        shengdiao = int(pinyin[-1])
        pinyin = pinyin[:-1]
    else:
        shengdiao = 0 # 有的字没有声调
    vec = np.zeros((len(alps)+1, ))
    cnts = Counter(pinyin)
    for c in cnts:
        if c not in alps:
            continue
        i = alps.index(c)
        vec[i] = cnts[c]
    vec[-1] = shengdiao
    return vec


def vector(word):
    vector1 = np.zeros(32)
    for char in word:
        bh = load_bihua_voc(char)
        zm = zimu_vec(char)
        # 拼接向量
        char_voc = np.concatenate((bh, zm))
        vector1 += char_voc
        # print(vector1)
    return vector1 / len(word)


def get_handian_sim(word1, word2):
    """
    汉典相似度计算
    :param word1:
    :param word2:
    :return:
    """
    # t1 = time.time()
    voc_1 = vector(word1)
    voc_2 = vector(word2)
    sim = similarity_cosine(voc_1, voc_2)
    # print('-----handian-sim:', time.time() - t1)
    return sim


print(get_handian_sim('苹果', '葡萄'))
